package cn.db101.api.complex.utils

import cn.hutool.core.codec.Base64
import cn.hutool.core.util.HexUtil
import java.security.KeyFactory
import java.security.Signature
import java.security.spec.PKCS8EncodedKeySpec
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec

/**
 *
 * @author：zooooooooy
 * @date: 2024/1/29 - 17:23
 */
object RSACLS {

    fun sign(content: String, privateKey: String?): String? {
        try {
            val priPKCS8 = PKCS8EncodedKeySpec(Base64.decode(privateKey))
            val keyf = KeyFactory.getInstance("RSA")
            val priKey = keyf.generatePrivate(priPKCS8)
            val signature = Signature.getInstance("SHA1WithRSA")
            signature.initSign(priKey)
            signature.update(content.toByteArray(charset("UTF-8")))
            val signed = signature.sign()
            return Base64.encode(signed)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    fun desEncrypt(data: String?): String? {
        try {
            val deskey: SecretKey = SecretKeySpec("36D6380B54D887639E763A14".toByteArray(charset("UTF-8")), "DESede")
            val cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding")
            cipher.init(Cipher.ENCRYPT_MODE, deskey)

            return HexUtil.encodeHexStr(cipher.doFinal(data?.toByteArray(charset("UTF-8"))), false)
        } catch (ex: java.lang.Exception) {
            //加密失败，打日志
            ex.printStackTrace()
        }
        return null
    }
}
